import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/pages/login/login/login_logic.dart';
import 'package:flutter_yn_goods/pages/login/register/register_logic.dart';
import 'package:flutter_yn_goods/pages/main_logic.dart';
import 'package:flutter_yn_goods/user/model/app_user_info_model.dart';
import 'package:flutter_yn_goods/utils/http/http_export.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/utils/shared/shared_export.dart';
import 'package:get/get.dart';

/// 记录登录后用户信息
///
class AppUserManager {
  static final AppUserManager _instance = AppUserManager._();

  factory AppUserManager() => _instance;

  AppUserManager._();

  // bool _firstLaunched = false;
  Rxn<AppUserInfoModel> user = Rxn();
  String sessionId = "";
  String token = "";

  int get uid => user.value?.id ?? 0;

  bool isLeader() {
    return user.value?.isLeader == 1;
  }

  bool get isLogin => (user.value?.id ?? 0) > 0;

  void initDataSource() {
    // if (user.value == null) {
    var info = SharedStorage().prefs.getString(SharedKey.userInfo) ?? "";
    if (info.isNotEmpty) {
      try {
        var userInfo = AppUserInfoModel.fromJson(jsonDecode(info));
        user.value = userInfo;
        clog("refreshUserInfo:$userInfo");
      } catch (e) {
        clog("refreshUserInfo:$info");
        clog("e=$e");
      }
    }
    // }
  }

  void remove() {
    sessionId = "";
    token = "";

    user.value = null;

    SharedStorage().prefs.remove(SharedKey.token);
    SharedStorage().prefs.remove(SharedKey.userInfo);

    // AppLocation.curLocation = null;
  }

  //0退出即可
  Future<void> logout() async {
    if (Get.currentRoute == AppRoutes.login ||
        Get.currentRoute == AppRoutes.register ||
        Get.isRegistered<LoginLogic>() ||
        Get.isRegistered<RegisterLogic>()) {
      return;
    }

    user.value = null;
    remove();
    if (Get.isRegistered<MainLogic>()) {
      // Get.find<MainLogic>().addPageView();
      Get.find<MainLogic>().currentIndex.value = 0;
      Get.find<MainLogic>().pageController.jumpToPage(0);
    }
    // Get.offAllNamed(AppRoutes.login);
  }

  String getToken() {
    return SharedStorage().prefs.getString(SharedKey.token) ?? '';
    // checkTokenExpired();
    // return token;
  }

  Future refreshUserInfo({bool isAgency = false}) async {
    var res = await HttpManager().get(
      (isLeader() || isAgency) ? API.accountLeaderInfo : API.accountInfo,
      fromJson: AppUserInfoModel.fromJson,
    );
    if (res.isSuccess) {
      user.value = res.data;
      // HttpManager().get(API.getOrderList,
      //   params: {
      //     'page': 1,
      //     'limit': 10,
      //   },
      //   // fromJson: ModelHome.fromJson
      // );
      SharedStorage()
          .prefs
          .setString(SharedKey.userInfo, jsonEncode(user.value?.toJson()));
    }
  }

  //1:男 0:女
  Future<HttpResponse> saveUserInfo(
      {String? nickname,
      String? avatar,
      String? age,
      String? pwd,
      // List? images,
      String? sex,
      String? mail,
      // String? province,
      // String? city,
      // String? area,
      String? address,
      // String? cityName,
      bool showLoading = false}) async {
    var params = <String, dynamic>{};
    // if (nickname != null) {
    //   params['nickname'] = nickname;
    // } else {
    //   params['nickname'] = AppUserManager().user.value?.nickname;
    // }

    params['avatar'] = avatar ?? AppUserManager().user.value?.avatar;
    params['nickname'] = nickname ?? AppUserManager().user.value?.nickname;
    // if (sex != null) {
    //   params['sex'] = sex;
    // } else {
    //   params['sex'] = AppUserManager().user.value?.sex;
    // }
    params['sex'] = sex ?? AppUserManager().user.value?.sex;
    if (pwd != null) {
      params['pwd'] = pwd;
    } else {
      // params['pwd'] = AppUserManager().user.value?.p;
    }

    // if (age != null) {
    //   params['age'] = age;
    // } else {
    //   params['age'] = AppUserManager().user.value?.age;
    // }
    params['age'] = age ?? AppUserManager().user.value?.age;
    // if (mail != null) {
    //   params['mail'] = mail;
    // } else {
    //   params['mail'] = AppUserManager().user.value?.mail;
    // }
    params['mail'] = mail ?? AppUserManager().user.value?.mail;
    // if (address != null) {
    params['address'] = address ?? AppUserManager().user.value?.address;
    // } else {
    //   params['address'] = AppUserManager().user.value?.address;
    // }

    // if (province != null) {
    //   params['province'] = province;
    //   params['city'] = city;
    //   params['area'] = area;
    //   params['address'] = address;
    //   params['city_name'] = cityName;
    // } else {
    //   params['province'] = AppUserManager().user.value?.province;
    //   params['city'] = AppUserManager().user.value?.city;
    //   params['area'] = AppUserManager().user.value?.area;
    //   params['address'] = AppUserManager().user.value?.address;
    //   params['city_name'] = AppUserManager().user.value?.cityName;
    // }
    var response = await HttpManager().post(
      API.accountEdit,
      params: params,
      uiType: showLoading ? HttpUIType.loading : HttpUIType.none,
    );

    if (response.isSuccess) {
      refreshUserInfo();
    }
    return response;
  }

  ///只有刷新sessionId和token的时候才是自动登录，其他都是手动登录
  Future<HttpResponse> login(String account, String password,
      {bool isAgency = false}) async {
    var response = await HttpManager().post(
        isAgency ? API.loginAgency : API.login,
        params: {"phone": account, "password": password},
        uiType: HttpUIType.loadingAndToast);

    if (response.isSuccess) {
      SharedStorage().prefs.setString(SharedKey.token, response.data['token']);
      SharedStorage().prefs.setString(SharedKey.account, account);

      await refreshUserInfo(isAgency: isAgency);
      if (Get.isRegistered<MainLogic>()) {
        // Get.find<MainLogic>().addPageView();
        Get.find<MainLogic>().currentIndex.value = 0;
        Get.find<MainLogic>().pageController.jumpToPage(0);
      }
    }
    return response;
  }
}
